import EventEmitter from "events";
import MuseumLogin from "../middleware/museumLogin";
import { getUserInfo } from "../thirdServices/museumApi";
import { AddUser } from "../services/museumUser";
import MuseumTimesTask from "../task/museumTimesTask";

class MuseumUserMange {
  private list: MuseumLogin[] = [];
  private emitter = new EventEmitter();
  constructor() {
    this.emitter.addListener('addMuseumUser', (item: { id: number, token: string }) => this.addUser(item));
    this.emitter.addListener('cancelAddMuseumUser', (id) => this.cancelAddUser(id));
  }

  addTask(loginTask: MuseumLogin) {
    loginTask.awaitAddUser(this.emitter);
    this.list.push(loginTask);
  }

  async addUser(item: { id: number, token: string }) {
      const { token, id} = item;
      this.list = this.list.filter((obj) => obj.id !== id);
      try {
        const res = await getUserInfo(token);
        if (res.data.code === 200) {
          const userInfo = res.data.user;
          if ( userInfo.phoneNumber) {
            await AddUser(userInfo.userId, userInfo.userName, userInfo.nickName, userInfo.phoneNumber, token);
          } else {
            console.log(`${userInfo.nickName}:${userInfo.userId} 没有在微信中登陆过`)
          }

          // 添加 times表
          const task = new MuseumTimesTask();
          task.executeByUser({ ...userInfo, token });
        }
      } catch (error) {
        console.log(error);
      }
  }

  cancelAddUser(id) {
    this.list = this.list.filter((obj) => obj.id !== id);
  }
}

export default MuseumUserMange;